/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import dk.redia.lib.net.ImageCache;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.xmlrpc.XmlRpcClientResultListener;
import dk.redia.lib.xmlrpc.XmlRpcResultDumper;
import dk.redia.lib.xmlrpc.XmlRpcResultUtils;
import dk.redia.libraryapp.activityutils.LibraryAppActivity;
import dk.redia.libraryapp.model.Externals;
import dk.redia.libraryapp.model.ObjectExtras;
import dk.redia.libraryapp.model.Reservation;
import dk.redia.libraryapp.model.SearchResultDataItem;
import dk.redia.libraryapp.utils.CategoryNamingUtils;
import dk.redia.libraryapp.xmlrpc.library.XmlRpcClient;

public class OthersBySameAuthorActivity extends LibraryAppActivity {

	public static final String EXTRAS_KEY_EXTERNALS = "externals";

	protected static final String logTag = "OthersBySameAuthorActivity";

	private LinearLayout itemsLinearLayout;
	private Externals externals;
	private LayoutInflater inflater;
	private Map<String, LinearLayout> identifierViews;
	private Map<String, LinearLayout> coverIdViews;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
	    identifierViews = new HashMap<String, LinearLayout>();
	    coverIdViews = new HashMap<String, LinearLayout>();
	    
	    externals = (Externals)getIntent().getParcelableExtra(EXTRAS_KEY_EXTERNALS);
		inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		
	    setContentView(R.layout.othersbysameauthor);
	    itemsLinearLayout = (LinearLayout)findViewById(R.id.othersBySameAuthorActivityItemsLinearLayout);
	    
	    for (SearchResultDataItem srdi : externals.getOthersByAuthorItems()) {
	    	LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.searchresultitem, null);

	    	if (srdi.hasValidCoverId()) { 
	    		coverIdViews.put(srdi.getCoverId(), layout);
	    	}
	    	if (srdi.hasValidIdentifier()) {
	    		identifierViews.put(srdi.getIdentifier(), layout);
	    	} else {
	    		layout.findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.GONE);
	    	}	    	
	    	
	    	layout.setTag(srdi);
	    	
	    	TextView descriptionTextView = (TextView)layout.findViewById(R.id.searchResultItemDescriptionTextView);
	    	TextView titleTextView = (TextView)layout.findViewById(R.id.searchResultItemTitleTextView);
	    	TextView itemCreatorTextView = (TextView)layout.findViewById(R.id.searchResultItemCreatorTextView);
	    	TextView categoryTextView = (TextView)layout.findViewById(R.id.searchResultItemCategoryTextView);
	    	ProgressBar itemLoadingProgressBar = (ProgressBar)layout.findViewById(R.id.searchResultItemLoadingProgressBar);

	    	itemLoadingProgressBar.setVisibility(View.INVISIBLE);
	    	descriptionTextView.setText(""); // FIXME Missing description
	    	titleTextView.setText(srdi.getTitle());
	    	itemCreatorTextView.setText(srdi.getCreator());
	    	categoryTextView.setText(CategoryNamingUtils.getCategoryName(srdi.getType()));
	    	itemsLinearLayout.addView(layout);
	    	itemsLinearLayout.addView(inflater.inflate(R.layout.listdivider, null));
	    }	
	    
	    XmlRpcClient.getInstance().getObjectExtras(
	    		AppConfiguration.getInstance().getCustomerId(), 
	    		AppConfiguration.getInstance().getApiKey(), 
	    		identifierViews.keySet().toArray(new String[] {}), 
	    		new XmlRpcClientResultListener() {
			
			@Override
			public void callFailed(String message) {
				Log.w(logTag, "Failed to retrieve extra information about objects");
				for (String key : identifierViews.keySet()) {
					identifierViews.get(key).findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.INVISIBLE);
				}
			}
			
			@Override
			public void callCompleted(Object resultObj) {
				XmlRpcResultDumper.dump(resultObj);
				Map<String, Object> resultMap = XmlRpcResultUtils.unpackStandardResult(resultObj);
				if (resultMap!=null && resultMap.containsKey("result")) {
					if ((Boolean)resultMap.get("result")) {
						Map<String, Object> dataMap = XmlRpcResultUtils.unpackStruct(resultMap.get("data"));
						if (dataMap!=null) {
							for (String key : dataMap.keySet()) {
								Map<String, Object> valueMap = XmlRpcResultUtils.unpackStruct(dataMap.get(key));
								if (valueMap != null && identifierViews.containsKey(key)) {
									ObjectExtras oe = ObjectExtras.fromMap(valueMap);
									LinearLayout itemView = identifierViews.get(key);
									itemView.findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.GONE);
									TextView titleTextView = (TextView)itemView.findViewById(R.id.searchResultItemTitleTextView);
									View reserveButton = itemView.findViewById(R.id.searchResultItemReserveButton);
									reserveButton.setVisibility(oe.isReservable ? View.VISIBLE : View.INVISIBLE);
									Reservation reservation = new Reservation();
									reservation.setReservationId(oe.reservationId);
									reservation.setTitle(titleTextView.getText().toString());
									reserveButton.setTag(reservation);
								}
							}
						} else {
							for (String key : identifierViews.keySet()) {
								identifierViews.get(key).findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.INVISIBLE);
							}
						}
					} else {
						Log.w(logTag, "Failed to retrieve object extras: " + resultMap.get("message"));
						for (String key : identifierViews.keySet()) {
							identifierViews.get(key).findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.INVISIBLE);
						}
					}
				} else {
					Log.w(logTag, "Invalid result data");
					for (String key : identifierViews.keySet()) {
						identifierViews.get(key).findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.INVISIBLE);
					}
				}
			}
		});
	    
	    XmlRpcClient.getInstance().getCoverUrl(
	    		AppConfiguration.getInstance().getCustomerId(), 
	    		AppConfiguration.getInstance().getApiKey(), 
	    		coverIdViews.keySet().toArray(new String[] {}), 
	    		new XmlRpcClientResultListener() {
			
			@Override
			public void callFailed(String message) {
				Log.w(logTag, "Failed to retrieve cover information");
			}
			
			@Override
			public void callCompleted(Object resultObj) {
				XmlRpcResultDumper.dump(resultObj);
				Map<String, Object> resultMap = XmlRpcResultUtils.unpackStandardResult(resultObj);
				if (resultMap!=null && resultMap.containsKey("result")) {
					if ((Boolean)resultMap.get("result")) {
						Map<String, Object> dataMap = XmlRpcResultUtils.unpackStruct(resultMap.get("data"));
						if (dataMap!=null) {
							for (String key : dataMap.keySet()) {
								if (coverIdViews.containsKey(key)) {
									LinearLayout itemView = coverIdViews.get(key);
									ImageView coverView = (ImageView)itemView.findViewById(R.id.searchResultItemCoverImageView);
									String coverUrl = (String)dataMap.get(key);
									if (coverUrl!=null && coverUrl!="") {
										try {
											ImageCache.getInstance().loadImage(new URL(coverUrl), coverView, null, 75, 125);
										} catch (MalformedURLException e) {
											Log.w(logTag, "Invalid cover URL: " + coverUrl);
										}
									}
									//Map<String, Object> valueMap = XmlRpcResultUtils.unpackStruct(dataMap.get(key));
								
									//ObjectExtras oe = ObjectExtras.fromMap(valueMap);
									//itemView.findViewById(R.id.searchResultItemReservingProgressBar).setVisibility(View.GONE);
									//itemView.findViewById(R.id.searchResultItemReserveButton).setVisibility(oe.isReservable ? View.VISIBLE : View.INVISIBLE);
								}
							}
						}
					} else {
						Log.w(logTag, "Failed to retrieve cover urls: " + resultMap.get("message"));
					}
				} else {
					Log.w(logTag, "Invalid result data");
				}
			}
		});
	    
    }
	
	public void onSearchResultItemClicked(View v) {
		SearchResultDataItem srdi = (SearchResultDataItem)v.getTag();
		Intent intent = new Intent(this, SearchResultDetailsActivity.class);
		intent.putExtra(SearchResultDetailsActivity.extraKeySearchResultDataItem, srdi);
		startActivity(intent);
	}

}
